
function AjoutAgenceController($scope, $rootScope, UploadManager, Agence) {
	$scope.scAgence = null;/*instance objet Agence*/
	$scope.alerts = [];/*pile des alertes*/
	$scope.submitted = false;
	$scope.files = [];
	$scope.percentage = 0;

	var _agenceId; // identifiant de l'agence

	var addAlert = function(typeAlert, msgAlert) {
		$scope.alerts.push({type: typeAlert, msg: msgAlert});
	};

	$scope.closeAlert = function(index) {
		$scope.alerts.splice(index, 1);
	};

	var resetForm = function () {
		$scope.agence = null;
		$scope.submitted = false;		
		$scope.files = [];
    }
	
    var UploadImage = function () {
		if( $scope.agence.imageUrl != "" ) {
        	UploadManager.uploadLast();
		}
    };

    $rootScope.$on('fileAdded', function (e, call) {
        $scope.files[0] = call;

        if( $scope.agence == null ){
        	$scope.agence = {imageUrl : call.name};
        } else {
			$scope.agence.imageUrl = call.name;// on met à jour la valeur dans le model avec le nom de l'image
        }


        $scope.$apply();
    });

    $rootScope.$on('uploadProgress', function (e, call) {
        $scope.percentage = call;
        $scope.$apply();
    });

    $rootScope.$on('uploadDone', function () {
    	redirectionNouvelleAgence ( _agenceId );
    });

    $scope.removeImage = function() {
		$scope.files = [];
		$scope.agence.imageUrl = "";	  
	}

	$scope.post = function( isValid ) {
		
		if( !isValid ) {
			$scope.submitted = true;
			return false;
		}

		$scope.scAgence = new Agence($scope.agence);
		$scope.scAgence.ajouterAgence().then(function(e){
			_agenceId = e.data.id;

			document.getElementById('id').value = _agenceId;

			addAlert('success', "L'agence " + e.data.libelle + " a \351t\351 correctement ajout\351e en base.");

			UploadImage();
		}).then(function() {
			var imageUrl = $scope.agence.imageUrl;

			if( typeof imageUrl == "undefined" || imageUrl == "" ) {
				redirectionNouvelleAgence ( _agenceId );
			}
			resetForm();
		});
	};
	
	var redirectionNouvelleAgence = function (agenceId) {
		window.location.href="/agence/edition?id=" + agenceId;
    }

	$scope.cancel = function() {
		resetForm();
	}
}
